import React, { Component } from 'react';
import {
    StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { Common } from '../../../component/common/Common.js';
import { style } from '../../../theme/style';
import { ScrollView } from 'react-navigation';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import MethodUtil from '../../../utils/MethodUtil';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const select = require('../../../imgs/select.png');
const OFFER_STATUS_LIST = [
    {
        dictName: '全部状态',
    }, {
        dictName: '待生效',
        dictKey: [1]
    }, , {
        dictName: '已拒绝',
        dictKey: [2]
    }, {
        dictName: '已撤销',
        dictKey: [3, 4]
    }, {
        dictName: '已生效',
        dictKey: [5]
    }, {
        dictName: '部分转成交',
        dictKey: [6]
    }, {
        dictName: '全部转成交',
        dictKey: [7]
    }
]
export class OfferDetail extends Component {
    static navigationOptions = ({ navigation, navigationOptions }) => {
        let { headTitle } = navigation.state.params || {};
        return {
            headerTitle: headTitle,
            headerTintColor: style.color.white,
            headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
            headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
            headerStyle: {  // 头部整体样式 
                elevation: 0,
                borderBottomWidth: 0,
                backgroundColor: style.color.themeColor
            },
            headerTitleStyle: {
                flex: 1,
                textAlign: 'center'
            }
        }
    };

    constructor(props) {
        super(props)
        let { resourceId, status, type, bidPackageId, bidId, applyId } = props.navigation.state.params || {}
        this.state = {
            status: 'data',
            options: [],
            isModal: false,
            listData: [], // 列表数据
            selectIndex: 0,
            refreshIcon: false, // 下拉刷新图标
            isCommentsModal: false,
            comments: '',
            type: type
        }
        this.reload = true; // 判断是整个页面刷新还是下拉刷新
        this.totalPage = 1; // 总页数
        this.pageParams = { // TODO
            bidPackageId: bidPackageId,
            resourceId: resourceId,
            searchKey: '',
            statusArry: status,
            pageNo: 1,
            pageSize: 10,
            applyId: applyId || null
        };
        this.packageParams = {
            bidPackageId: bidPackageId,
            bidId: bidId,
            applyId: applyId || null
        }
    }

    async componentWillMount() {
        await this.initPage();
    }

    async initPage() {
        this.setState({
            status: this.reload ? 'loading' : 'data',
            refreshIcon: !this.reload && this.pageParams.pageNo == '1'
        })
        let res
        if (this.state.type == 'package') {
            res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_DETAIL), this.packageParams);
            if (res) {
                this.setState({
                    status: res && res.length > 0 ? 'data' : 'empty',
                    listData: res,
                    refreshIcon: false
                })
            } else {
                this.setState({
                    refreshIcon: false,
                    status: 'error'
                })
            }
        }
        else {
            res = await HTTP.POST(API_GENERATE(API.RESOURECE_DETAIL_LIST), this.pageParams);
            if (res) {
                this.totalPage = res.totalPage;
                this.setState({
                    status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
                    listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
                    refreshIcon: false
                })
            } else {
                this.setState({
                    refreshIcon: false,
                    status: 'error'
                })
            }
        }

    }

    onErrorRefresh = () => {
        this.initPage();
    }

    // 刷新页面
    reloadPage = () => {
        this.pageParams.pageNo = 1;
        this.reload = true;
        this.initPage();
    }

    async refresh() {
        this.pageParams.pageNo = 1;
        this.reload = false;
        await this.initPage();
    }

    // 上拉翻页
    loadMore = () => {
        if (this.totalPage > this.pageParams.pageNo) {
            this.pageParams.pageNo++;
            this.reload = false;
            this.initPage();
        }
    }

    _selectCallBack = (index) => {
        this.setState({
            isModal: false,
            selectIndex: index,
        }, () => {
            this.pageParams.statusArry = OFFER_STATUS_LIST[this.state.selectIndex].dictKey;
            this.reloadPage();
        })
    }

    // 搜索View
    _renderFilterWrap() {
        return (
            <View>
                {this.state.type == 'unlimited' ?
                    <View style={styles.filterWrap}>
                        <View style={{ flex: 1 }}>
                            <Image source={searchIcon} style={styles.searchIcon} />
                            <TextInput
                                ref="enterpriseInput"
                                style={styles.searchInput}
                                underlineColorAndroid='transparent'
                                placeholder={"请输入企业/商品"}
                                placeholderTextColor="rgba(255, 255, 255, .8)"
                                maxLength={30}
                                returnKeyType={'search'}
                                defaultValue={this.pageParams.searchKey}
                                onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
                                onSubmitEditing={() => { this.reloadPage(); }}
                            />
                        </View>
                        <TouchableOpacity onPress={() => { this.setState({ isModal: true }) }}
                            style={{ paddingLeft: 20 * scale, flexDirection: "row", alignItems: "center", height: 36 * scale }}>
                            <Text style={{ color: "#fff", marginRight: 5 }}>{OFFER_STATUS_LIST[this.state.selectIndex].dictName}</Text>
                            <Image source={select} style={{ width: 10, height: 5, tintColor: '#fff' }} />
                        </TouchableOpacity>
                    </View> : null
                }

            </View>
        )
    }
    _renderListItem = (data) => {
        let { companyName, createTime, goodsName, statusDictKeyName, quantity, intentionQuantity, price, totalPrice, udPrice,
            payTypeName, payStyleName, deliveryTypeName, transportTypeName, destAddress, bizStaffName, comments, organName, tranReportType, status, bidPackageId,
            bidId, bidOrderGroupId, bizStaffId, corpId, corpName, salesType, bizModel, competQuantity
        } = data.item
        return (
            <View>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 * scale }}>
                    <Text style={{ fontSize: 11 }}>{companyName}</Text>
                    <Text style={{ fontSize: 11 }}>{createTime}</Text>
                </View>
                <View style={styles.offerDetailItem}>
                    <View style={{ flexDirection: 'row', marginBottom: 16 * scale, paddingHorizontal: 20 * scale, justifyContent: 'space-between' }}>
                        <Text style={{ fontSize: 13, fontWeight: '600' }}>{goodsName}</Text>
                        <Text style={{ fontSize: 11, color: '#E02020' }}>{statusDictKeyName}</Text>
                    </View>
                    <View style={styles.offerDetailHorizontal}>
                        <View style={styles.offerDetailBox}>
                            <Text style={styles.offerDetailTitle}>报盘量</Text>
                            <Text style={styles.offerDetailText}>{quantity ? quantity + '吨' : '-'}</Text>
                        </View>
                        <View style={styles.offerDetailBox}>
                            <Text style={styles.offerDetailTitle}>可执行量</Text>
                            <Text style={styles.offerDetailText}>{bizModel === 'P' ? (competQuantity ? competQuantity + '吨' : '-') : (intentionQuantity ? intentionQuantity + '吨' : '-')}</Text>
                        </View>
                    </View>
                    <View style={styles.offerDetailHorizontal}>
                        <View style={styles.offerDetailBox}>
                            <Text style={styles.offerDetailTitle}>含税单价</Text>
                            <Text style={styles.offerDetailText}>{price ? '¥' + price + '/吨' : '-'}</Text>
                        </View>
                        <View style={styles.offerDetailBox}>
                            <Text style={styles.offerDetailTitle}>总金额</Text>
                            <Text style={styles.offerDetailText}>{totalPrice ? '¥' + MethodUtil.toThousands(totalPrice || 0, 2) : '-'}</Text>
                        </View>
                    </View>
                    <View style={styles.offerDetailHorizontal}>
                        <View style={styles.offerDetailBox}>
                            <Text style={styles.offerDetailTitle}>升贴水</Text>
                            <Text style={styles.offerDetailText}>{udPrice ? '¥' + udPrice + '/吨' : '-'}</Text>
                        </View>
                    </View>
                    {payStyleName || deliveryTypeName || transportTypeName || destAddress ?
                        <View style={{ backgroundColor: '#F4F7FE', borderRadius: 6, paddingHorizontal: 20 * scale, paddingVertical: 8 * scale, marginHorizontal: 10 * scale }}>
                            <Text style={{ color: '#979797', fontSize: 11 * scale, lineHeight: 24 * scale }}>{payTypeName ? payTypeName + '|' : ''}
                                {payStyleName ? payStyleName + ' | ' : ''}
                                {deliveryTypeName ? deliveryTypeName + ' | ' : ''}
                                {transportTypeName ? transportTypeName + ' | ' : ''}
                                {destAddress ? '客户配送地址' + destAddress : ''}
                            </Text>
                            {comments ?
                                <TouchableOpacity onPress={() => { this.setState({ isCommentsModal: true, comments: comments }) }}>
                                    <Text style={[styles.offerItemTitle, { color: '#0091FF', marginTop: 10 * scale }]}>
                                        [客户备注]
                  </Text>
                                </TouchableOpacity> : null
                            }
                        </View> : null
                    }

                    {bizStaffName ?
                        <View>
                            <Text style={{ fontSize: 11 * scale, color: '#060606', marginTop: 10 * scale, marginLeft: 20 * scale }}>
                                {tranReportType === 'N' ? '敞口现货 |' : null} {tranReportType === 'Q' ? '泉化 |' : null} {bizStaffName ? bizStaffName + '(' + organName + ')' + ' | ' : ''}
                                {/* {status==5?<Text style={[styles.offerItemTitle,{color:'#0091FF'}]} onPress={()=>{ this.props.navigation.navigate('ToClaimList',{searchKey:bidPackageId,beginDate:null,endDate:null,checkedAll:false})}}>[意向认领]</Text>:null} */}
                                {status == 5 || status == 6 || status == 7 ? <Text style={[styles.offerItemTitle, { color: '#0091FF' }]} onPress={() => {
                                    this.props.navigation.navigate('TurnOrderInfo', {
                                        bidId,
                                        tranReportType,
                                        bizStaffId,
                                        bidOrderGroupId,
                                        orderType: salesType,
                                        choice: {
                                            corpId,
                                            corpName
                                        }
                                    })
                                }}>[意向转单]</Text> : null}
                            </Text>
                        </View> : null
                    }

                </View>
            </View>
        )
    }
    render() {
        let { selectIndex, isModal, status, refreshIcon, listData, isCommentsModal, comments } = this.state;
        let { totalPrice, purchaseQty } = this.props.navigation.state.params || {}
        return (
            <View style={styles.container}>
                {this._renderFilterWrap()}
                {this.state.type == 'package' ?
                    <View style={styles.itemBottom}>
                        <Text style={{ fontSize: 12 * scale }}>成交总额：
						<Text style={{ fontSize: 12 * scale, fontWeight: '600' }}>
                                ¥{MethodUtil.toThousands(totalPrice || 0, 2)}
                            </Text>
                        </Text>
                        <Text style={{ fontSize: 12 * scale }}>成交总量：
						<Text style={{ fontSize: 12 * scale, fontWeight: '600' }}>
                                {purchaseQty}
                            </Text>
                            吨
					</Text>
                    </View>
                    : null
                }
                {
                    status == 'data' ? (
                        <View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale }}>
                            <FlatList
                                data={listData}
                                style={{ marginLeft: 20 * scale, marginRight: 20 * scale }}
                                renderItem={this._renderListItem}
                                refreshing={refreshIcon}
                                onRefresh={() => { this.refresh() }}
                                onEndReachedThreshold={0.1}
                                onEndReached={() => { this.loadMore() }}
                            />
                        </View>) : <PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />
                }
                <Common type="modal" demoData={(
                    <Common type="listRadio" selectIndex={selectIndex} title={'状态'} listData={OFFER_STATUS_LIST} selectCallBack={this._selectCallBack} />
                )} isVisible={isModal} closeCallballFn={() => { this.setState({ isModal: false }) }} />
                <Common type="modal" demoData={(
                    <View style={styles.commentsBody}>
                        <Text style={styles.commentsTitle}>备注</Text>
                        <Text style={styles.commentContent}>{comments}</Text>
                    </View>
                )} isVisible={isCommentsModal} closeCallballFn={() => { this.setState({ isCommentsModal: false }) }} />
            </View>
        )
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: style.color.bgGray,
    },
    filterWrap: {
        height: 76 * scale,
        paddingVertical: 20 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 30 * scale,
        backgroundColor: style.color.themeColor,
    },
    searchInput: {
        flex: 1,
        width: '100%',
        paddingLeft: 50 * scale,
        paddingRight: 12 * scale,
        backgroundColor: 'rgba(255, 255, 255, .18)',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 0,
        position: 'relative',
        borderRadius: 8 * scale,
        color: '#fff',

    },
    searchIcon: {
        width: 20 * scale,
        height: 22 * scale,
        position: 'absolute',
        left: 20 * scale,
        top: 8 * scale,
        zIndex: 9,
        opacity: 0.8,
    },
    tabWrap: {
        backgroundColor: style.color.themeColor,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'flex-start',
        paddingLeft: 18 * scale,
        paddingRight: 18 * scale,
        paddingBottom: 150 * scale
    },
    tabText: {
        color: '#fff',
        textAlign: 'center'
    },
    tabTextBottom: {
        marginTop: 7 * scale,
        height: 2 * scale,
        width: '100%'
    },
    tabItem: {
        paddingTop: 14 * scale,
        paddingBottom: 12 * scale,
        paddingHorizontal: 30 * scale,
    },
    offerBox: {
        flex: 1,
        marginTop: -150 * scale,
        marginHorizontal: 20 * scale
    },
    offerItem: {
        backgroundColor: '#fff',
        paddingVertical: 14 * scale,
        paddingHorizontal: 20 * scale,
        borderRadius: 6 * scale,
        marginBottom: 16 * scale
    },
    offerDetailItem: {
        backgroundColor: '#fff',
        paddingVertical: 14 * scale,
        borderRadius: 6 * scale,
        marginBottom: 16 * scale
    },
    offerTitle: {
        fontSize: 13,
        color: '#000000',
        fontWeight: "600"
    },
    offerContent: {
        marginTop: 7 * scale,
        backgroundColor: '#F4F7FE',
        borderRadius: 6 * scale,
        paddingVertical: 10 * scale,
    },
    offerHorizontal: {
        flexDirection: "row",
        alignItems: 'center',
        marginBottom: 25 * scale
    },
    offerContentItem: {
        flex: 1,
        alignItems: 'center'
    },
    offerItemTitle: {
        fontSize: 11 * scale,
        marginBottom: 10 * scale
    },
    offerItemText: {
        fontSize: 11 * scale,
    },
    offerData: {
        marginBottom: 8 * scale,
        flexDirection: 'row',
        alignItems: 'center'
    },
    offerDetailBox: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    offerDetailTitle: {
        width: 42 * scale,
        textAlign: 'right',
        marginRight: 16 * scale,
        fontSize: 10,
        color: '#979797'
    },
    offerDetailText: {
        fontSize: 12,
        color: '#446FD9',
        width: 80 * scale,
        marginRight: 30 * scale
    },
    offerDetailHorizontal: {
        flexDirection: 'row',
        paddingHorizontal: 20 * scale,
        // justifyContent:'space-between',
        marginBottom: 12 * scale
    },
    commentsBody: {
        width: 300 * scale,
        paddingLeft: 25 * scale,
        paddingRight: 17 * scale,
        paddingBottom: 30 * scale,
        backgroundColor: '#fff',
        borderRadius: 13 * scale
    },
    commentsTitle: {
        fontSize: 12 * scale,
        color: style.color.darkGray,
        paddingTop: 15 * scale,
        paddingBottom: 15 * scale
    },
    commentContent: {
        fontSize: 12 * scale,
        paddingTop: 15 * scale,
        paddingBottom: 15 * scale
    },
    itemBottom: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingVertical: 12 * scale,
        paddingHorizontal: 20 * scale,
    }
})